#include "head.h"

int net_puts(request_t *request, int net_fd, MYSQL *mysql){
    // printf("net_puts start\n");
    LOG(INFO, request->user_name, "puts", "puts start");
    MYSQL_RES *res;
    MYSQL_ROW row = NULL;

    response_t response;
    bzero(&response, sizeof(response));

    int user_id = get_user_id(request->user_name, mysql);
    if(user_id == -1){
        response.status = 1;
        sprintf(response.args, "User information error.\n");
        send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);
        return -1;
    }

    char query[1024] = {0};
    char str[160] = {0};
    strcpy(str, request->path);
    if(strcmp(str, "/")){
        strcat(str, "/");
    }
    strcat(str, request->args);
    sprintf(query, "select * from files \
            where filename = '%s' and user_id = %d \
            and path = '%s' and delete_flag = 1",
            request->args, user_id, str);
    //查找文件
    if(mysql_query(mysql, query)){
        // printf("%s\n", mysql_error(mysql));
        LOG(ERROR, request->user_name, "puts select", mysql_error(mysql));
        sprintf(response.args, "Server error.\n");
        send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);
        return -1;
    }

    send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);

    //获取结果集
    res = mysql_store_result(mysql);
    if(res != NULL){
        row = mysql_fetch_row(res);
    }
    recv_file(row, user_id, net_fd, request, mysql);

    mysql_free_result(res);
    return 0;
}

